package com.example.huixingzheng.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.example.huixingzheng.fragment.WeatherFragment;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.json.JSONObject;

import java.util.Date;

public class MQTTClient {
    private static final String TAG = "MQTTClient";
    private MqttClient client;
    private String serverUri; // MQTT 服务器地址
    private String clientId; // 客户端ID
    private String topic; // 订阅的主题
    private String username;
    private String password;
    private Context context; // Android 上下文
    private DatabaseHelper dbHelper;

    public MQTTClient(String serverUri, String clientId, String username, String password, String topic, Context context) {
        this.serverUri = serverUri;
        this.clientId = clientId;
        this.username = username;
        this.password = password;
        this.topic = topic;
        this.context = context;
        this.dbHelper = new DatabaseHelper(context);
    }

    public void connect() {
        try {
            // 使用 MemoryPersistence 作为持久化存储
            client = new MqttClient(serverUri, clientId, new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true); // 设置是否清除会话
            options.setAutomaticReconnect(true); // 设置自动重连
            options.setConnectionTimeout(10); // 设置超时时间
            options.setUserName(username);
            options.setPassword(password.toCharArray());

            // 连接到 MQTT 服务器
            client.connect(options);

            // 设置消息回调
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    Log.e(TAG, "Connection lost: " + cause.getMessage());
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    Log.d(TAG, "Message arrived: " + new String(message.getPayload()));
                    // 处理接收到的消息
                    processMessage(new String(message.getPayload()));
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    Log.d(TAG, "Delivery complete");
                }
            });

            // 订阅主题
            client.subscribe(topic);

        } catch (MqttException e) {
            Log.e(TAG, "MQTT connection error: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private void processMessage(String message) {
        try {
            JSONObject json = new JSONObject(message);
            // 提取温度、湿度、烟雾浓度等数据
            double temperature = json.getDouble("Temperature");
            double humidity = json.getDouble("RelativeHumidity");
            double smokeLevel = json.getDouble("Smokescope");
            double lightLux = json.getDouble("LightLux");
            // 存储数据到数据库
            saveDataToDatabase("Device1", temperature, humidity, smokeLevel, lightLux);
        } catch (Exception e) {
            Log.e(TAG, "Error processing message: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private void saveDataToDatabase(String deviceName, double temperature, double humidity, double smokeLevel, double lightLux) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("DeviceName", deviceName);
        values.put("Time", new Date().toString());
        values.put("Temperature", temperature);
        values.put("Smokescope", smokeLevel);
        values.put("LightLux", lightLux);
        values.put("RelativeHumidity", humidity);
        values.put("Account", "your_account"); // 这里需要替换为实际的账户名

        long newRowId = db.insert("RpiData", null, values);
        if (newRowId == -1) {
            Log.e(TAG, "Error saving data to database");
        } else {
            Log.d(TAG, "Data saved to database with ID: " + newRowId);
        }
        db.close();
    }

    public void setCallback(WeatherFragment.MqttCallbackHandler mqttCallbackHandler) {
    }

}